import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/counter_providers.dart';
import 'riverpod_detail_screen.dart';

/// Riverpod Demo主屏幕
/// 展示如何使用Consumer和ref来监听状态变化
class RiverpodDemoScreen extends ConsumerWidget {
  const RiverpodDemoScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Riverpod Demo'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            onPressed: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) => const RiverpodDetailScreen(),
                ),
              );
            },
            icon: const Icon(Icons.info_outline),
            tooltip: 'View Details',
          ),
        ],
      ),
      body: const SingleChildScrollView(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 用户信息卡片
            _UserInfoCard(),
            SizedBox(height: 16),

            // 计数器显示卡片
            _CounterDisplayCard(),
            SizedBox(height: 16),

            // 操作按钮区域
            _ActionButtonsSection(),
            SizedBox(height: 16),

            // 状态信息卡片
            _StatusInfoCard(),
            SizedBox(height: 16),

            // 设置卡片
            _SettingsCard(),
          ],
        ),
      ),
    );
  }
}

/// 用户信息卡片
/// 展示如何使用Consumer监听特定状态
class _UserInfoCard extends ConsumerWidget {
  const _UserInfoCard();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 监听用户名变化
    final username = ref.watch(usernameProvider);

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'User Information',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),

            Row(
              children: [
                const Icon(Icons.person),
                const SizedBox(width: 8),
                Text('Welcome, $username!'),
              ],
            ),

            const SizedBox(height: 8),

            // 用户名输入框
            TextField(
              decoration: const InputDecoration(
                labelText: 'Enter your name',
                border: OutlineInputBorder(),
              ),
              onSubmitted: (value) {
                // 使用ref.read来调用方法
                ref.read(counterProvider.notifier).setUsername(value);
              },
            ),
          ],
        ),
      ),
    );
  }
}

/// 计数器显示卡片
/// 展示如何显示计数器的值和状态
class _CounterDisplayCard extends ConsumerWidget {
  const _CounterDisplayCard();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 监听多个状态
    final count = ref.watch(counterValueProvider);
    final status = ref.watch(statusProvider);

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            const Text(
              'Counter Value',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            // 显示计数器值
            Text(
              '$count',
              style: Theme.of(context).textTheme.headlineLarge?.copyWith(
                color: Theme.of(context).primaryColor,
                fontWeight: FontWeight.bold,
              ),
            ),

            const SizedBox(height: 8),

            // 显示状态
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
              decoration: BoxDecoration(
                color: _getStatusColor(status),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                status,
                style: const TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'Zero':
        return Colors.grey;
      case 'Low':
        return Colors.green;
      case 'Medium':
        return Colors.orange;
      case 'High':
        return Colors.red;
      default:
        return Colors.blue;
    }
  }
}

/// 操作按钮区域
/// 展示各种操作按钮
class _ActionButtonsSection extends ConsumerWidget {
  const _ActionButtonsSection();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 监听加载状态
    final isLoading = ref.watch(isLoadingProvider);

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Actions',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            // 基本操作按钮
            Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              alignment: WrapAlignment.spaceEvenly,
              children: [
                ElevatedButton.icon(
                  onPressed: () =>
                      ref.read(counterProvider.notifier).increment(),
                  icon: const Icon(Icons.add, size: 18),
                  label: const Text('+1'),
                ),
                ElevatedButton.icon(
                  onPressed: () =>
                      ref.read(counterProvider.notifier).decrement(),
                  icon: const Icon(Icons.remove, size: 18),
                  label: const Text('-1'),
                ),
                ElevatedButton.icon(
                  onPressed: () => ref.read(counterProvider.notifier).reset(),
                  icon: const Icon(Icons.refresh, size: 18),
                  label: const Text('Reset'),
                ),
              ],
            ),

            const SizedBox(height: 12),

            // 批量操作按钮
            Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              alignment: WrapAlignment.spaceEvenly,
              children: [
                OutlinedButton(
                  onPressed: () =>
                      ref.read(counterProvider.notifier).addMultiple(5),
                  child: const Text('+5'),
                ),
                OutlinedButton(
                  onPressed: () =>
                      ref.read(counterProvider.notifier).addMultiple(10),
                  child: const Text('+10'),
                ),
                OutlinedButton(
                  onPressed: () =>
                      ref.read(counterProvider.notifier).addMultiple(100),
                  child: const Text('+100'),
                ),
              ],
            ),

            const SizedBox(height: 12),

            // 异步操作按钮
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: isLoading
                    ? null
                    : () => ref.read(counterProvider.notifier).incrementAsync(),
                icon: isLoading
                    ? const SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Icon(Icons.cloud_upload),
                label: Text(isLoading ? 'Loading...' : 'Async +1'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 状态信息卡片
/// 展示如何监听多个派生状态
class _StatusInfoCard extends ConsumerWidget {
  const _StatusInfoCard();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 监听多个派生状态
    final count = ref.watch(counterValueProvider);
    final username = ref.watch(usernameProvider);
    final status = ref.watch(statusProvider);
    final isLoading = ref.watch(isLoadingProvider);
    final isEven = ref.watch(isEvenProvider);
    final nextMilestone = ref.watch(nextMilestoneProvider);

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Status Information',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),

            Column(
              children: [
                _buildStatusRow('Current Value', '$count', Icons.numbers),
                _buildStatusRow('Status', status, Icons.info),
                _buildStatusRow('User', username, Icons.person),
                _buildStatusRow(
                  'Loading',
                  isLoading ? 'Yes' : 'No',
                  isLoading ? Icons.hourglass_empty : Icons.check,
                ),
                _buildStatusRow(
                  'Is Even',
                  isEven ? 'Yes' : 'No',
                  isEven ? Icons.check_circle : Icons.cancel,
                ),
                _buildStatusRow('Next Milestone', nextMilestone, Icons.flag),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusRow(String label, String value, IconData icon) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        children: [
          Icon(icon, size: 20),
          const SizedBox(width: 8),
          Text('$label: '),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(fontWeight: FontWeight.bold),
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }
}

/// 设置卡片
/// 展示如何管理应用设置
class _SettingsCard extends ConsumerWidget {
  const _SettingsCard();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final settings = ref.watch(settingsProvider);
    final theme = ref.watch(themeProvider);

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Settings',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),

            // 主题设置
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('Theme'),
                DropdownButton<String>(
                  value: theme,
                  items: const [
                    DropdownMenuItem(value: 'light', child: Text('Light')),
                    DropdownMenuItem(value: 'dark', child: Text('Dark')),
                    DropdownMenuItem(value: 'auto', child: Text('Auto')),
                  ],
                  onChanged: (value) {
                    if (value != null) {
                      ref
                          .read(settingsProvider.notifier)
                          .updateSetting('theme', value);
                    }
                  },
                ),
              ],
            ),

            // 通知设置
            SwitchListTile(
              title: const Text('Notifications'),
              value: settings['notifications'] ?? true,
              onChanged: (value) {
                ref
                    .read(settingsProvider.notifier)
                    .updateSetting('notifications', value);
              },
            ),

            // 自动保存设置
            SwitchListTile(
              title: const Text('Auto Save'),
              value: settings['autoSave'] ?? false,
              onChanged: (value) {
                ref
                    .read(settingsProvider.notifier)
                    .updateSetting('autoSave', value);
              },
            ),

            // 重置设置按钮
            const SizedBox(height: 8),
            SizedBox(
              width: double.infinity,
              child: OutlinedButton(
                onPressed: () =>
                    ref.read(settingsProvider.notifier).resetSettings(),
                child: const Text('Reset Settings'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
